import json
import pygame,pygame.sprite
from Item import item
import random,animal



class Window:
    def __init__(self):
        #加载图标的参数
        self.init()
    def loadNum(self):
        with open("config\ScreenConfig.json","r",encoding="utf-8") as f:
            data = json.load(f)
            # 屏幕宽高
            self.Width = data["Width"]
            self.Height = data["Height"]
            # 地图网格数，网格大小
            self.Numgrid = data["Numgrid"]
            self.Gridsize = data["Gridsize"]
            #设置帧率
            self.Fps = data["FPS"]
            self.Resize = (data["ItemResize"],data["ItemResize"])
            self.ScoreFontPos = (data["ScoreFontPosX"],data["ScoreFontPosY"])
        #x向间隔，y向间隔
    def loadItem(self):
        #初始化交换逻辑
        self.key = 0
        self.Change = []
        #存储item类的精灵组
        self.ItemGroup = pygame.sprite.Group()


        with open("config/ItemName.json","r",encoding="utf-8") as f:
            ItemImagePath = json.load(f)["path"]

        with open("config/ItemNameHide.json","r",encoding="utf-8") as f:
            ItemHideImagePath = json.load(f)["path"]

        #Itemimages预加载pygame.image -> Item类的图像
        self.ItemImages = {}
        self.ItemHide = {}
        self.ItemImagesName = []
        #对地址切片，切出图片的名字，作为字典的键
        for path in ItemImagePath:
            start = 0
            end = -1
            for i in range(len(path)):
                if path[i] == '/':
                    start = i
                elif path[i] == '.':
                    end = i
            name = path[start+1:end]
            self.ItemImagesName.append(name)
            #初步预加载图像
            originalImage = pygame.image.load(path)
            hidepath = 'image/'+name+'_hidden.png'
            originalHideImage = pygame.image.load(hidepath)
            #缩放至 resize*resize
            self.ItemImages[name] = pygame.transform.smoothscale(originalImage, self.Resize)
            self.ItemHide[name] = pygame.transform.smoothscale(originalHideImage, self.Resize)
        #如上，预生成阴影图片
    def loadWindow(self):
        #创建pygame对象
        #建立窗口
        size = (self.Width,self.Height)
        self.Screen = pygame.display.set_mode(size)
        #创建标题
        pygame.display.set_caption("三消测试")
        self.loadItem()
        self.CreateMapItem()
        self.ScoreFont = pygame.font.SysFont('Arial', 36)
        self.Score = 0
    def init(self):
        #集成初始化代码
        #载入数字选项
        self.loadNum()
        #载入pygame类
        pygame.init()

        self.Xmargin = (self.Width - self.Numgrid * self.Gridsize) // 2
        self.Ymargin = (self.Height - self.Numgrid * self.Gridsize) // 2
        self.loadWindow()
    def drawLine(self,Input):
        #窗口名：self.Screen
        #Input:[line_color,start_pos,end_pos,line_width]
        pygame.draw.line(self.Screen,Input[0],Input[1],
                         Input[2],Input[3])
    def CreateItem(self,pos):
        name = random.choice(self.ItemImagesName)
        image = self.ItemImages[name]
        hideimage = self.ItemHide[name]
        step_0 = item(name,image,pos,hideimage)
        self.ItemGroup.add(step_0)
    def CreateMapItem(self,xmargin=0,ymargin=0,Gridsize=0):
        if not xmargin:
            xmargin = self.Xmargin
        if not ymargin :
            ymargin = self.Ymargin
        if not Gridsize:
            Gridsize = self.Gridsize

        # 图像边界的规定
        self.LeftBorder = xmargin
        self.TopBorder = ymargin

        #建立矩阵,用于下文的消除逻辑
        self.ItemMap = [[[self.LeftBorder+(1/2+j)*Gridsize,self.TopBorder+(1/2+i)*Gridsize] for j in range(self.Numgrid)] for i in range(self.Numgrid)]
        #创建各个网格中的图标对象
        for i in range(self.Numgrid):
            for j in range(i):
                #批量处理x方向的图标
                Xpos = self.ItemMap[i][j]
                self.CreateItem(Xpos)
                #批量处理y方向的图标
                Ypos = self.ItemMap[j][i]
                self.CreateItem(Ypos)
            #对角线图标的创建
            Mpos = self.ItemMap[i][i]
            self.CreateItem(Mpos)
    def ShowScore(self):
        text = self.ScoreFont.render(f"{self.Score}",True,(0,0,0))
        text_rect = text.get_rect(center=(self.ScoreFontPos))
        self.Screen.blit(text,text_rect)
    def CreateMap(self,xmargin=0,ymargin=0,Gridsize=0):
        if not xmargin:
            xmargin = self.Xmargin
        if not ymargin :
            ymargin = self.Ymargin
        if not Gridsize:
            Gridsize = self.Gridsize
        color = 'black'
        lineWidth = 1
        for i in range(self.Numgrid+1):
            #先横向画线，再纵向画线
            #横向画线
            Xstart_pos = ((xmargin),(ymargin+i*Gridsize))
            Xend_pos = ((xmargin+self.Numgrid*Gridsize),(ymargin+i*Gridsize))
            XInput = [color,Xstart_pos,Xend_pos,lineWidth]
            self.drawLine(XInput)
            #纵向画线
            Ystart_pos = ((xmargin+i*Gridsize),(ymargin))
            Yend_pos = ((xmargin+i*Gridsize),(ymargin+self.Numgrid*Gridsize))
            YInput = [color,Ystart_pos,Yend_pos,lineWidth]
            self.drawLine(YInput)
        self.ItemGroup.draw(self.Screen)
        self.ShowScore()

    def CheckItem(self,MousePos):
        for Item in self.ItemGroup:
            if Item.rect.collidepoint(MousePos):
                Item.image,Item.hideImage = Item.hideImage,Item.image
                self.Change.append(Item)
                self.key+=1
                if self.key == 2:
                    #进入检查交换逻辑
                    #重置判断器，并取出两个精灵
                    self.key = 0
                    Item_1 , Item_2 = self.Change[0],self.Change[1]
                    Item_1.image, Item_1.hideImage = Item_1.hideImage, Item_1.image
                    Item_2.image, Item_2.hideImage = Item_2.hideImage, Item_2.image
                    self.Change = []
                    animal.ItemChange(self.Screen,Item_1,Item_2,self.Gridsize,self.Fps,5000)
    def MoveItemAdd(self,LoadList,Item_0,Item_1,Item_2):
        if Item_0.name == Item_1.name == Item_2.name:
            if Item_0 not in LoadList:
                LoadList.append(Item_0)
                self.Score+=10
            if Item_1 not in LoadList:
                LoadList.append(Item_1)
                self.Score += 10
            if Item_2 not in LoadList:
                LoadList.append(Item_2)
                self.Score += 10
            # print(self.ItemGroup)
    def NormalCheckItem(self):
        #逻辑（待优化）：对每个格子中的对象进行四个方向上的检测
        #加载当前的图标
        NowMap = [[None for j in range(self.Numgrid)] for i in range(self.Numgrid)]
        for i in range(len(self.ItemMap)):
            for j in range(len(self.ItemMap)):
                pos = self.ItemMap[i][j]
                key = False
                for Item in self.ItemGroup:
                    #将目前的这个点代入ItemGroup进行检测，若有，则在当前矩阵中加载
                    if Item.rect.collidepoint(pos):
                        NowMap[i][j] = Item
                        key = True
                if not key:
                    # 若没有，则上面的物体向下掉落一格
                    if i == 0 :
                        self.CreateItem(self.ItemMap[0][j])
                    else:
                        for _ in range(i-1,-1,-1):
                            DropItem = NowMap[_][j]
                            NextPos = self.ItemMap[_+1][j]
                            if DropItem:
                                animal.DropAnimal(DropItem,NextPos)

        MoveItem = []
        for i in range(len(self.ItemMap)):
            for j in range(len(self.ItemMap)-2):
                Item_0 = NowMap[i][j]
                if Item_0 :
                    Item_1 = NowMap[i][j+1]
                    Item_2 = NowMap[i][j+2]
                    if Item_1 and Item_2:
                    # x方向检测
                        self.MoveItemAdd(MoveItem,Item_0,Item_1,Item_2)
                Item_3 = NowMap[j][i]
                if Item_3:
                    Item_4 = NowMap[j+1][i]
                    Item_5 = NowMap[j+2][i]
                    if Item_5 and Item_4:
                    # # y方向检测
                         self.MoveItemAdd(MoveItem,Item_3,Item_4,Item_5)
        for item in MoveItem:
            self.ItemGroup.remove(item)













